<?php

namespace App\Http\Middleware;

use App\Models\RoleUser;
use Closure;
use App\Models\Company;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class CompanyCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(empty(Auth::user())){
            return redirect('/');
        }
        if(empty(Auth::user()->comuser())){
            return redirect('/');
        }
        $com = Company::where('id',Auth::user()->comuser()->corpid)->first();
        if(empty($com))
        {
            abort(403,'企业信息有误');
        }
        if($com->status == 2)
        {
            abort(403,'企业违规被封停,请联系青苜绩效客服');
        }
        if($com->expire_at < date('Y-m-d H:i:s',time()))
        {
            $comuserid = Auth::user()->comuser()->id;
            $admin = RoleUser::where('corpid',Auth::user()->comuser()->corpid)->where('role_id',9)->first();
            $adminid = $admin->user_id;
            if($adminid == $comuserid){
                if(is_mobile()){
                    return redirect('/cashier');
                }else{
                    return redirect('/buy-vip');
                }
            }else{
                abort(403,'企业VIP已到期,请联系管理员续费');
            }
        }
        return $next($request);
    }
}
